const events=require('events');
const crypto=require('crypto');
const router=require('koa-router')();
const passport=require('koa-passport');
const checkNotLogin=require('../middlewares/checkNotLogin');
const {User}=require('../models/index');
const config=require('../config/config');

router.get('/github',checkNotLogin(),passport.authenticate('github'));

router.get('/github/callback',(ctx,next)=>{
    return passport.authenticate('github',async (err,data,token)=>{
        if(err)return next(err);
        let ee=new events();
        ee.on('fail',msg=>{
            ctx.flash={error:msg};
            ctx.redirect('/login');
        })
        if(!data)return ee.emit('fail','Github验证错误');

        let user={
            name:data.username,
            password:crypto.createHash('md5').update([data.username,data._json.email,config.secret].join()).digest('hex'),
            email:data._json.email,
            avatar:data._json.avatar_url,
            regTime:new Date(),
            token:crypto.createHash('md5').update([config.secret,data.username,data._json.email].join('&')).digest('hex'),
            github:data.profileUrl,
            auth:{
                thirdName:'Github',
                id:data.id,
                username:data.username,
                profileUrl:data.profileUrl,
                email:data._json.email,
                avatar:data._json.avatar_url,
                token
            },
            intro:data._json.bio
        };

        let ret=await User.findOneAndUpdate({name:user.name},user,{upsert:true,rawResult:true});

        if(!ret)return ee.emit('fail','保存Github用户失败');

        let loginUser;
        if(!ret.value){//首次使用此Github帐号授权登录
            loginUser={
                _id:ret.lastErrorObject.upserted,
                name:user.name,
                email:user.email,
                avatar:user.avatar,
                score:0,
                intro:user.intro,
                auth:user.auth
            };
        }else{//已经使用过此Github帐号授权登录
            loginUser={
                _id:ret.value._id,
                name:ret.value.name,
                email:ret.value.email,
                avatar:ret.value.avatar,
                score:0,
                intro:ret.value.intro,
                auth:ret.value.auth
            };
        }

        ctx.session.loginUser=loginUser;
        ctx.flash={success:'登录成功'};
        ctx.redirect('/');

    })(ctx,next);
});

module.exports=router;